var data1 = [{'id':'1','operationtype':'修改类型','operationman':'修改人员','operationdate':'time','modificationcontent':'内容','customername':'text1','email':'text2','cucustomerpost':'text3','phone':'text4','mobilephone':'text5','customerwechat':'text6','expressaddress':'text7','customerbirthday':'text8','customerremark':'text9','customerman':'text10'}];

var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,upload = layui.upload
    ,userphotos="",
    form = layui.form,$ = layui.jquery,id=getQueryVariable("id")
    ,customercode=""
    ,wjs=[]
    ,fileNames=[]
    ,file_count=0;
/*var processid="";//window.sessionStorage.getItem("processid");
if(processid !=""){
    $("#tjsp").css("display","none");
    $("#save").css("display","none");
    $('#editor-form').find('input,textarea,select').attr('disabled',true);

}*/
var  salesmanCodes="";
var userTree=JSON.parse(window.sessionStorage.getItem("userTree"));
var customerType=getdictionary(6,44);//流程审批类型
var codeqz=getdictionary(6,46);//前缀
var codehz=getdictionary(6,47);//扣缀
var qz=$("select[name='qz']");//前缀
var hz=$("select[name='hz']");//后缀
var salmanValue=[];//回显业务员值
qz.append(getoption(codeqz));
hz.append(getoption(codehz));

var customerinfoSpstatus=JSON.parse(window.sessionStorage.getItem("customerinfoSpstatus"));
if(id==""){//新增
    $(".layui-card-header")[0].innerText="新增客户";
    $(".layui-card-header")[0].innerText="新增客户";

}else{//修改
    $(".layui-card-header")[0].innerText="修改客户";
    $('#addfilediv').html("");
}
//自定义表单验证
form.verify({
    validateBankCard: function(value, item){ //value：表单的值、item：表单的DOM对象
        if(!/^([1-9]{1})(\d{14}|\d{18})$/.test(value) && value!= ""){
            return '请输入正确的银行卡账号';
        }
    }
});
getlxandlevel();
//表单初始值，修改时调用
if(id!=""){
    /*form.val("editor-form",{
        "customerabbreviation":"进入修改客户",
    })
    form.render();*/
   /* $("#logoadd").css("display","none");
    $("#userphotosdel").css("display","none");*/
    $("input[name='code']").attr("readOnly",true);
    init();//加载数据
    if (customerinfoSpstatus>=3){//审批通过了
        $("input[name='abbreviation']").attr("readOnly",true);
        // $("input[name='shortCode']").attr("readOnly",true);
        $("#name")[0].readOnly=true;
        //审批通过的客户没有提交审批按钮
        document.getElementById("tjsp").style.display="none";
    }
}else{
    form.val("editor-form",{
        "salesman":user.name
    })
    form.render();

    //新增时才有点击事件
    //此处为单击编码输入框弹出编码生成选择框
    $("#code").on("click",function () {

        //layer.msg("点击编码");
        layer.open({
            type: 1,
            title: "申请编码",
            area: ['400px', '250px'],
            content: $("#selectCode")//引用的弹出层的页面层的方式加载修改界面表单
        });
    });
}
// select下拉框选中触发事件
form.on("select", function(data){
   /* if(data.elem.name=="type"){
        var tf=false;
       for(var i=0;i<customerType.length;i++){
          if(data.value==customerType[i].code){
              tf=true;
          }
       }
       if(!tf){
          $("#tjsp").css("display","none");
       }else{
           $("#tjsp").css("display","block");
       }
       form.render();
    }*/
    //alert(data.value); // 获取选中的值
});
//---客户联系人查询
table.render({
    elem: '#customerselect'
    //,data:data1
    ,type:"get"
    ,url:"customercontact/selectByPage"
    ,where:{
        "company":customercode
    }
    ,toolbar: '#customertoolbar'
    ,cols: [[
        {checkbox: true, fixed: true}
        ,{field:'name', title:'联系人名称', sort: true}
        ,{field:'email', title:'邮箱地址', sort: true}
        ,{field:'post', title:'职务', sort: true}
        ,{field:'tel', title:'电话', sort: true}
        ,{field:'phone', title:'手机', sort: true}
        ,{field:'wx', title:'微信', sort: true}
        ,{field:'expressAddress', title:'联系人快递地址', sort: true}
        ,{field:'birthday', title:'联系人生日', sort: true}
        ,{field:'remark', title:'联系人备注', sort: true}
       // ,{field:'salesman', title:'业务员', sort: true}
        ,{fixed: 'right', width:150, align:'center', toolbar: '#customerup', title:'操作'}
    ]]
    ,id: 'customertableid'
    ,page: true
    ,height:300
});
//联系人工具按钮,新增、删除
table.on('toolbar(customertable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    var data = checkStatus.data;
    switch(obj.event){
        case 'new':
            if(id==""){
                layer.msg("请先保存客户信息");
                break;
            }
            layer.open({
                type: 2,
                area: ['908px', '650px'],
                content: "views/jsp/BasicData/tpl/newcustomer.jsp"
            });
            break;
        case 'delet':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList.length==0){
                layer.msg("请选择要删除的数据");
                break;
            }
            if(del(delList)){
                layer.msg("删除成功");
                table.reload('customertableid', {
                    type: 'get'
                    ,url:"customercontact/selectByPage"
                    ,where:{
                        "company":customercode
                    }
                    ,   page: {
                        curr: 1 //重新从第 1 页开始
                    }


                }, 'data');
            }else{
                layer.msg('删除失败');
            }
            break;
    };
});
table.on('tool(customertable)', function(obj){
    var data = obj.data;
    if(obj.event === 'customerup') {
        layer.open({
            type: 2,
            area: ['908px', '650px'],
            content: "views/jsp/BasicData/tpl/newcustomer.jsp?id="+obj.data.id
        });
    }else if(obj.event === 'customerde') {
        layer.confirm('真的删除行么', function (index) {
            obj.del();
            layer.close(index);
        });
    }
});

//---日志
table.render({
    elem: '#infoselect'
    //,data:data1
    ,type:"GET"
    ,url:"customerlog/selectByPage"
    ,where:{
        "companycode":customercode
    }
    ,cols: [[
        {field:'type', title:'操作类型', sort: true}
        ,{field:'optioner', title:'操作员', sort: true}
        ,{field:'optionTime', title:'操作日期', sort: true}
        ,{field:'content', title:'修改内容', sort: true}
    ]]
    ,id: 'infoselecttableid'
    ,page: true
    ,height:350
});
/*
//上传图片
upload.render({
    elem: '.uploadimg'
    , url: 'https://httpbin.org/post'
    ,before: function(obj) {
        var thin = this;
        obj.preview(function(index, file, result){
            $("#"+thin.id+"").attr('src', result); //图片链接（base64）
        });

    }
    ,done: function(res){
        //如果上传失败
        if(res.code > 0){
            return layer.msg('上传失败');
        }
        //上传成功
    }
    ,error: function(){
        layer.msg('上传失败,请稍后重试')
    }
})*/
//客户logo
upload.render({
    elem: '#logoadd'
    , url: 'ftp/uploadFile'
    , field: "uploadify"     //添加这个属性与后台名称保存一致
    , accept: 'file' //允许上传的文件类型
    ,data:{"fileType":"customerlogo"}//头像
    ,before: function(obj) {
        /*var thin = this;
        obj.preview(function(index, file, result){
            $("#"+thin.id+"").attr('src', result); //图片链接（base64）
        });*/

    }
    ,done: function(res){
        //如果上传失败
        if(res.status !=200){
            return layer.msg('上传失败');
        }else{
            var ftpPath=res.data[0].ftpPath;
            var fileName=res.data[0].fileName;
            var src=getFtpPath(ftpPath,fileName);
            $("#userphotos").attr('src',src);
            $("input[name='logo']")[0].value=src;
        }
        //上传成功
    }
    ,error: function(){
        layer.msg('上传失败,请稍后重试')
    }
})

$("#userphotosdel").on('click',function () {
    $("#userphotos").attr('src','');
    //userphotos = "";
    $("input[name='logo']")[0].value="";
})
$("#shared").on('click',function () {
    layer.open({
        type: 2,
        area: ['1488px', '800px'],
        content: 'views/jsp/BasicData/tpl/shared.jsp'
    });
})
//关闭
$("#shutdown").on('click',function () {
   // parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp"+(id==''?'':'?id='+id));
    setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/BasicData/customercenter.jsp");
        parent.intab("views/jsp/BasicData/customercenter.jsp","客户中心")
        parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp","添加客户信息");
        parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp"+(id==''?'':'?id='+id));
    },1000)
    return false;
})
//打印
$("#print").on("click",function () {
    if(id==""){
        layer.msg('新增不可打印');
    }else{
        window.open("views/jsp/report.jsp?ym=customer&code=code:"+customercode);
        /*layer.open({
            type: 2,
            area: ['1488px', '800px'],
            content: 'views/jsp/BasicData/tpl/print.jsp?id='+id
        });*/
    }
});

$("#spbm").on('click',function () {
   // var checkeds = $("input[name='radio']:checked").val();

    /*form.val("editor-form",{
        "code":"dadfasf"
    })
    form.render();*/
    var hz=$("select[name='hz']")[0].value;
    var qz=$("select[name='qz']")[0].value;
    var code=getCode(1,qz,hz);
    form.val("editor-form",{
        "code":code
    })
    form.render();

});
$("#qx").on('click',function () {
   /* form.val("editor-form",{
        "code":"dd"
    })
    form.render();*/
    layer.closeAll();
});

//监听提交----提交审核
form.on('submit(customerinfo-form-submit)', function(data){
    if (!isRepeat(data.field.shortCode)){
        return false;
    }
    //提交审批进入待批箱
    data.field.spstatus="2";
    let res=save(data);

    if(res.flag){
        layer.msg('提交审核成功！')
    }else {
        layer.msg(res.msg+'提交失败');
        return false;
    }
    setTimeout(function () {
        //保存成功则刷新提交过来的界面 并关闭此页面
        parent.detab("views/jsp/BasicData/customercenter.jsp");
        parent.intab("views/jsp/BasicData/customercenter.jsp","客户中心")
        parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp"+(id==''?'':'?id='+id));
    },1000)
    return false;

   /* 此代码已无用
    var tfsp=true;
    for(var i=0;i<customerType.length;i++){
        if(data.field.type==customerType[i].code){
           tfsp=false;
           break;
        }
    }
    if(tfsp){
        layer.msg("此客户无须审批！");
        form.val("editor-form",{
            "spstatus":"2",
        })
        form.render();
       // data.field.spstatus="2";
    }else{
        data.field.spstatus="2";
        let res=save(data);

        if(res.flag){
          //  layer.msg('保存成功,开始提交审核！');

          //  processid=startProcess();
            layer.msg('提交审核成功！')
        }else {
            layer.msg(res.msg+'提交失败');
            return false;
        }

    }*/


   // tj();

   // var customer =  layui.table.cache["customertableid"]; //联系人表格数据
    // setTimeout(function () {
    //     //保存成功则刷新提交过来的界面 并关闭此页面
    //     parent.detab("views/jsp/BasicData/customercenter.jsp");
    //     parent.intab("views/jsp/BasicData/customercenter.jsp","客户中心")
    //     parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp"+(id==''?'':'?id='+id));
    // },1000)
    // setTimeout(function () {
    //     //保存成功则刷新提交过来的界面 并关闭此页面
    //     parent.detab("views/jsp/BasicData/customercenter.jsp");
    //     parent.intab("views/jsp/BasicData/customercenter.jsp","客户中心")
    //     parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp"+(id==''?'':'?id='+id));
    // },1000)
    // return false;
});
//监听提交---保存
form.on('submit(customerinfo-form-save)', function(data){
    if (!isRepeat(data.field.shortCode)){
        return false;
    }
    if (id==""){
        //保存进入草稿箱
        data.field.spstatus="1";
    }


    let res=save(data);
    if(res.flag){
        layer.msg('保存成功');
    }else {
        layer.msg(res.msg+'保存失败');
    }
    // setTimeout(function () {
    //     //保存成功则刷新提交过来的界面 并关闭此页面
    //     parent.detab("views/jsp/BasicData/customercenter.jsp");
    //     parent.intab("views/jsp/BasicData/customercenter.jsp","客户中心")
    //     parent.detab("views/jsp/BasicData/tpl/customerinfo.jsp"+(id==''?'':'?id='+id));
    // },1000)

    return false;
});
//保存客户信息
function  save(data) {
    if(data.field.salesman.indexOf(",") !=-1){
        layui.layer.msg("业务员只能选择一个！");
        return false;
    }

   /* var tfsp=true;
    for(var i=0;i<customerType.length;i++){
        if(data.field.type==customerType[i].code){
            tfsp=false;
          break;
        }
    }
    if(tfsp){
        data.field.spstatus="2";
    }*/
   // data.field.spstatus="0";//保存时审批状态为草稿
   // data.field.salesman=user.code;
    data.field.id=id;
    delete data.field.file;
    var tf=false;

    let res={};
    $.ajax({
        type : 'POST',
        data:JSON.stringify(data.field),
        url:'customer/insert',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                var objs=da.data.split(":");
                customercode=objs[0];
                id=objs[1];//ID为新增之后，返回来的id用于联系人保存
                res.flag=true;
            }else {
                res.msg=da.msg+", ";
                res.flag=false;
            }
        }
    });

    //将文件保存到文件目录中
    //data.wj=JSON.stringify(wjs);


    var customerdata={};
    customerdata.code=data.field.code;
    customerdata.name=data.field.abbreviation;
    customerdata.pid="3";
    customerdata.path=JSON.stringify(wjs);
   if(!insert(customerdata)){
       layer.msg("文件上传失败，请通过修改功能或文件模块进行文件的上传！");
   };
    return res;
}
function  insert(data) {
    if(data.path=="[]"){
        return true;
    }
    //if(id !="") data.id=id;
    var tf=false;
    $.ajax({
        type : 'post',
        //  url : 'resource/getTree',
        data:JSON.stringify(data),
        url:'wjcatalog/saveOrUpdate',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data==0?false:true;

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
//获取字典
function getdictionary(dl,xl) {
    var obj=[];
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data: {"type":dl,"lx":xl},
        url:'dictionary2/getValues',
        dataType:"json",
       // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                obj=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
return obj;
}
//获取客户类型、等级、跟进阶段
function getlxandlevel() {
  var djs=getdictionary(6,26);//客户等级
    let typeArray=[];
    var fls=getdictionary(6,27);//客户类型
    if (customerinfoSpstatus==3){//审批通过,客户类型中有合作类型
        typeArray=fls;
    }else {//未通过，去掉合作类型
        for (let i in fls) {
            if (fls[i].name.indexOf("合作")===-1){
                typeArray.push(fls[i]);
            }
        }
    }


    // var jds=getdictionary(6,28);//跟进阶段
    var aoc=getdictionary(1,87);//客户属性
    var country=getdictionary(6,29);//国家/地区
    var province=getdictionary(6,30);//港口/省份
    var city=getdictionary(6,31);//城市
   /* var bank=getdictionary(6,32);//开户银行*/
    var mainBusiness=getdictionary(1,4);//主营产品
    var sourceOfCustomers=getdictionary(1,3);//客户来源
    var businessType=getdictionary(6,33);//业务类型


    var typs=$("select[name='type']");//客户类型
    var level=$("select[name='level']");//客户等级
    // var  status=$("select[name='status']");//跟进阶段
    var  attributesOfCustomers=$("select[name='attributesOfCustomers']");//客户属性
    var countrys=$("select[name='country']");//国家/地区
    var provinces=$("select[name='province']");//港口/省份
    var citys=$("select[name='city']");//城市
   /* var banks=$("select[name='bank']");//开户银行*/
    var mainBusinesss=$("select[name='mainBusiness']");//主营产品
    var businessTypes=$("select[name='businessType']");//业务类型
    var sourceOfCustomerss=$("select[name='sourceOfCustomers']");//客户来源




    level.append(getoption(djs)); //客户等级
    typs.append(getoption(typeArray)); //客户类型
    // status.append(getoption(jds));//跟进阶段
    attributesOfCustomers.append(getoption(aoc));//客户属性
    countrys.append(getoption(country));//国家/地区
    provinces.append(getoption(province));//港口/省份
    citys.append(getoption(city));//城市
    /*banks.append(getoption(bank));//开户银行*/
    mainBusinesss.append(getoption(mainBusiness));//主营产品
    businessTypes.append(getoption(businessType));//业务类型
    sourceOfCustomerss.append(getoption(sourceOfCustomers));//客户来源

    form.render();

}
function  getoption(objs) {
    var stoptions="";
    for(var i=0;i<objs.length;i++){
        stoptions+="<option value='"+objs[i].code+"'>"+objs[i].name+"</option>";
    }
   return stoptions;
}

function init() {
    //获取客户信息
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data: {"id":id},
        url:'customer/selectByKey',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                setCustomer(da.data)
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
}

function getFile(code) {
    var obj=[];
    //获取客户信息
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data: {"code":code},
        url:'wjinfo/getFileByCataLogCode',
        dataType:"json",
        // contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
               obj=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return obj;
}
//客户信息赋值
function setCustomer(data) {
    form.val("editor-form",{
        "abbreviation":data.abbreviation,
        //"salesman":data.salesman,
        "code":data.code,
        "type":data.type,
        "name":data.name,
        "address":data.address,
        "country":data.country,
        "province":data.province,
        "city":data.city,
        "postcode":data.postcode,
        "phone":data.phone,
        "accountPeriod":data.accountPeriod?data.accountPeriod:0,
        "bank":data.bank,
        "bankaccount":data.bankaccount,
        "level":data.level,
        "mainBusiness":data.mainBusiness,
        "sourceOfCustomers":data.sourceOfCustomers,
        "businessType":data.businessType,
        // "homepage":data.homepage,
        "swiftcode":data.swiftcode,
        "followUpPeriod":data.followUpPeriod,
        "expressAddress":data.expressAddress,
        "paymentAccountNo":data.paymentAccountNo,
        "creditLine":data.creditLine?data.creditLine:0,
        "shortCode":data.shortCode,
        "attributesOfCustomers":data.attributesOfCustomers,
        "spstatus":data.spstatus,
    })
    salmanValue=eval("['"+data.salesman+"']");
    salesmanCodes=data.salesman;
    if(!data.logo==""){
        $("img#userphotos")[0].src=data.logo;
    }
    customercode=data.code;
//根据客户编码获取其文件
  var fjdata=  getFile(data.code);

    for(var i = 0;i<fjdata.length;i++){
        file_count ++;
        var filename=fjdata[0].split("filename=")[1];

        var newFile ='<div class="img_tj">'+
            '<div class="file_wdiv"><a id="file_span'+file_count+'" download="'+filename+'" href="'+fjdata[i]+'">'+filename+'</a><a type="button" class="layui-btn" id="fileUpload_'+file_count+'"><i class="layui-icon"></i>上传附件</a></div>'+
            '<div class="de_div">'+
            /* '<input name="file_instructions'+file_count+'" class="layui-input" placeholder="附件说明" value="'+fjdata[i].shuom+'">'+*/
            '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="fileUpload_sc_'+file_count+'"></i>'+
            '</div>'+
            '</div>';
        $('#addfilediv').append(newFile);
        uploadFileRender("#fileUpload_"+file_count,"#fileUpload_sc_"+file_count,"#file_span"+file_count);
    }

    form.render();
}
//删除联系人
function del(ids) {
    var tf=false;
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"ids":JSON.stringify(ids)},
        url:'customercontact/delete',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=true;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}
function startProcess() {
  var res="";
    $.ajax({
        type : 'get',
        //  url : 'resource/getTree',
        data:{"id":id},
        url:'customer/startProcess',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
  return res;
}

/**
 * 提交后禁用
 */
function tj() {
    $("#tjsp").css("display","none");
    $("#save").css("display","none");
    $('#editor-form').find('input,textarea,select').attr('disabled',true);
    form.render();
}

//文件
$("#newfile").on('click',function () {
    file_count ++;
    var newFile ='<div class="img_tj">'+
        '<div class="file_wdiv"><a id="file_span'+file_count+'"></a><a type="button" class="layui-btn" id="fileUpload_'+file_count+'"><i class="layui-icon"></i>上传附件</a></div>'+
        '<div class="de_div">'+
        /* '<input name="file_instructions'+file_count+'" class="layui-input" placeholder="附件说明">'+*/
        '<i class="layui-icon layui-icon-reduce-circle" style="font-size: 30px; color: #000000;line-height: 30px;" id="fileUpload_sc_'+file_count+'"></i>'+
        '</div>'+
        '</div>';
    $('#addfilediv').append(newFile);
    uploadFileRender("#fileUpload_"+file_count,"#fileUpload_sc_"+file_count,"#file_span"+file_count);
});

function uploadFileRender(e,uploadimd,name) {
    var uploadfile = upload.render({
        elem: e
        , url: 'ftp/uploadFile'
        , field: "uploadify"     //添加这个属性与后台名称保存一致
        , accept: 'file' //允许上传的文件类型
        ,data:{"fileType":"productwj"}//头像
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(name).html(file.name);
                $(name).attr("href",result);
                $(name).attr("download",file.name);
            });
        }
        , done: function (res) {


            //如果上传失败
            if (res.status !=200) {
                return layer.msg('上传失败');
            }
            //上传成功
            /*
                            var img_sb = file_wdiv.find('.img_sb');
                            if(img_sb.length != 0){
                                img_sb.remove();
                            }*/
           var srcFileName= res.data[0].originalFileName;
            var ftpPath=res.data[0].ftpPath;
            var fileName=res.data[0].fileName;
            var src=getFtpPath(ftpPath,fileName);
            wjs.push(srcFileName+"###"+src);
            return layer.msg('上传成功');

        }
        , error: function () {
            //演示失败状态，并实现重传
            var file_wdiv = $(e).parent();
            var img_sb = file_wdiv.find('.img_sb');
            if(img_sb.length == 0){
                file_wdiv.append('<div class="img_sb"><a class="layui-btn layui-btn-xs demo-reload">重试</a></div>');
                file_wdiv.find('.demo-reload').on('click', function () {
                    uploadfile.upload();
                });
            }
        }
    });
    $(uploadimd).on('click',function () {
        $(uploadimd).parent().parent().remove();
    })
}


function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            //return this
            salesmanCodes="";
            for(var i=0;i<change.length;i++){
                if(i == change.length-1){
                    salesmanCodes=salesmanCodes+ change[i].value;
                }else{
                    salesmanCodes=salesmanCodes+ change[i].value+",";
                }
            }

        }
    })
}
function initable22() {
//select over

//获取当前用户的部门及人员结构树
    let treeList = userTree;//getCurrentDepartmentUser2();ssssss

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        salesmanCodes= getxmselect("#salesman","salesman", userTree);
    }else {
        //  getxmselect("#operationCode","owneroperator", [{name: user.name, value: user.code}]);
        salesmanCodes= getxmselect("#salesman","salesman", [{name: user.name, value: user.code}]);
    }

}

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
initable22();
var salman=getxmselect("#salesman","salesman",salesmanCodes);
//新增时初始化业务员
if (id===""){
    salmanValue.push(user.code);
}
salman.setValue(salmanValue);

/*
$("input[name='abbreviation']")[0].onblur(function (data) {
alert(data);
});*/
$("#name").blur(function (data) {
   if(data.target.name=="name"){//名称
       isExist(data);
   }
   return false;
});
$("#abbreviation").blur(function (data) {
     if(data.target.name=="abbreviation"){//简称
         isExist(data);
     }
    return false;
});
function  isExist(data) {

    $.ajax({
        type:'get',
        //  url : 'resource/getTree',
        data:{"zd":data.target.name,"text":data.target.value,"id":id},
        url:'customer/isExist',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success:function (da) {
            if(da.status==200 ){
               if(da.data !=""){
                   layer.msg(da.data);
                  // $("input[name='"+data.target.name+"']")[0]="";
                   $("#"+data.target.name+"").val("");
               }
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
}

function isRepeat(data) {
    if (escape(data).indexOf("%u") !=-1){
        layer.msg("客户简码不能包含中文");
        return false;
    }
    if (data.length>3){
        layer.msg("客户简码只能填写三个字符");
        return false;
    }
    return true;
}